package com.ctvit.framework.interceptor;

import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
import org.apache.cxf.helpers.IOUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.io.CachedOutputStream;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.SingletonBeanRegistry;
import org.springframework.beans.factory.support.DefaultSingletonBeanRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;

public class WSLoggingInInterceptor extends AbstractSoapInterceptor implements ApplicationContextAware {
	private ConfigurableApplicationContext context;

	private DefaultSingletonBeanRegistry registry;
	public WSLoggingInInterceptor ()
    {
        super(Phase.RECEIVE);
    }
	
	public void handleMessage(SoapMessage arg0) throws Fault {
		//get the remote address
		SoapMessage message=arg0;
        HttpServletRequest httpRequest = (HttpServletRequest) message.get ( AbstractHTTPDestination.HTTP_REQUEST );
//        System.out.println ("Request From the address : " + httpRequest.getRemoteAddr ( ) );

        try
        {
            // now get the request xml
            InputStream is = message.getContent ( InputStream.class );
            CachedOutputStream os = new CachedOutputStream();
            IOUtils.copy( is, os );
            os.flush();
            message.setContent (  InputStream.class, os.getInputStream ( ) );
            is.close ( );
            String xmlRequest=IOUtils.toString ( os.getInputStream ( ) );
//            System.out.println ("The request is: " + IOUtils.toString ( os.getInputStream ( ) ));
            os.close ( );
//            registry = (DefaultSingletonBeanRegistry)context.getBeanFactory();
            if(registry.containsSingleton("xmlRequest")){
//            	registry.destroySingleton("xmlRequest");
            	throw new Exception("qqqqqq");
            }
            registry.registerSingleton("xmlRequest", xmlRequest);
        }

        catch ( Exception ex )
        {
            ex.printStackTrace ( );
        }


	}
	public void setApplicationContext(ApplicationContext applicationContext)
	    throws BeansException {
	
	context = (ConfigurableApplicationContext) applicationContext;
	registry = (DefaultSingletonBeanRegistry) context.getBeanFactory();
	
	}
}
